<template>
  <div class="FunctionalAuthority">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item><a>权限管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <main>
      <div class="search-con">
        <el-form :model="searchForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="角色关键字" prop="keyWord">
                <el-input
                  v-model="searchForm.keyWord"
                  placeholder="请输入角色名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="getList">查询</el-button>
              <el-button @click="searchForm.keyWord = ''">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table :data="tableData" border>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="创建日期" prop="create_time"></el-table-column>
        <el-table-column label="创建人" prop="creator">
          <template slot-scope="scope">
            <show-person :personInfo="scope.row.creator" />
          </template>
        </el-table-column>
        <el-table-column label="权限数量">
          <template slot-scope="scope">
            {{ getAuthNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="giveAuthority(scope.row)"
              :disabled="scope.row.code === 'sysadmin'"
              >赋权</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationInfo.current_page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="paginationInfo.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationInfo.total"
        background
      >
      </el-pagination>
    </main>
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      custom-class="funtional-authority-dialog"
      @close="onBeforeClose"
    >
      <div slot="title" class="dialog-title">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>系统管理</el-breadcrumb-item>
          <el-breadcrumb-item>权限管理</el-breadcrumb-item>
          <el-breadcrumb-item
            ><a>{{ selectedRow.name }}</a></el-breadcrumb-item
          >
        </el-breadcrumb>
      </div>
      <div class="dialog-main">
        <div class="main-left scroll-content">
          <h2>菜单权限</h2>
          <el-tree
            :data="leftTreeData"
            :props="{ label: 'menu_name' }"
            show-checkbox
            node-key="menu_code"
            ref="leftTree"
            :default-checked-keys="ldckeys"
            @check="leftTreeChecked"
          >
          </el-tree>
        </div>
        <div class="main-right scroll-content">
          <div class="right-top">
            <h2>功能权限</h2>
            <el-checkbox
              v-model="checked"
              :disabled="!rightTreeData.length"
              @change="checkAll"
              >全选</el-checkbox
            >
          </div>
          <el-tree
            :data="rightTreeData"
            :props="{ label: 'auth_name' }"
            show-checkbox
            :default-checked-keys="dckeys"
            node-key="auth_id"
            ref="rightTree"
            @check="rightTreeChecked"
          >
          </el-tree>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onBeforeClose">取 消</el-button>
        <el-button type="primary" @click="dialogSubmit">保存全部</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import showPerson from "@/components/public/showPerson.vue";
import { getAllRole, getAuthList, getLeftMenu, setAuth } from "@/http/api";
import dayjs from "dayjs";

export default {
  name: "FunctionalAuthority",
  components: { showPerson },
  data() {
    return {
      searchForm: {
        keyWord: "",
      },
      tableData: [],
      paginationInfo: {
        current_page: 1,
        total: 0,
        page_size: 10,
      },
      dialogVisible: false,
      selectedRow: {},
      leftTreeData: [],
      checked: false,
      rightTreeData: [],
      ldckeys: [],
      dckeys: [],
      leftTreeCheckedNodes: [],
      rightTreeCheckedNodes: [],
    };
  },
  async mounted() {
    this.getList();
    let res = await getLeftMenu();
    if (res.code === 20041) {
      this.leftTreeData = res.data.menu.filter(
        (item) => item.menu_code !== "main"
      );
    }
  },
  methods: {
    search() {},
    giveAuthority(row) {
      this.selectedRow = row;
      if (row.authority) {
        this.ldckeys = row.authority.menu;
        this.leftTreeChecked(null, {
          checkedNodes: row.authority.menu.map((item) => {
            return {
              menu_code: item,
            };
          }),
        });
        this.dckeys = row.authority.authority;
      }
      this.dialogVisible = true;
    },
    handleSizeChange() {
      console.log("handleSizeChange");
    },
    handleCurrentChange() {
      console.log("handleCurrentChange");
    },
    async leftTreeChecked(_, { checkedNodes }) {
      let res = await getAuthList(
        checkedNodes.map((item) => {
          return item.menu_code;
        })
      );
      if (res.code === 20041) {
        this.rightTreeData = res.data;
      }
      this.changeChecked();
      this.leftTreeCheckedNodes = checkedNodes;
    },
    onBeforeClose() {
      this.dialogVisible = false;
    },
    async dialogSubmit() {
      let res = await setAuth({
        menu: this.leftTreeCheckedNodes,
        authority: this.rightTreeCheckedNodes,
        role_code: this.selectedRow.code,
      });
      if (res.code === 20031) {
        this.$message.success("设置权限成功");
        window.location.reload()
        this.onBeforeClose();
      }
    },
    async getList() {
      let res = await getAllRole({
        ...this.paginationInfo,
        ...this.searchForm,
      });
      if (res.code === 20041) {
        this.paginationInfo = res.data.page;
        this.tableData = res.data.rows;
        this.tableData.forEach((item) => {
          item.create_time = dayjs(item.create_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
    },
    getAuthNumber(row) {
      if (row.authority && row.code !== "sysadmin") {
        let num = row.authority.menu.length + row.authority.authority.length;
        return num === 0 ? "" : num;
      } else {
        return "";
      }
    },
    checkAll() {
      if (this.checked) {
        this.$refs.rightTree.setCheckedNodes(this.rightTreeData);
        this.rightTreeCheckedNodes = Array.from(
          new Set(this.rightTreeCheckedNodes.concat(this.rightTreeData))
        );
        this.dckeys = this.rightTreeCheckedNodes.map((item) => item.auth_id);
      } else {
        this.$refs.rightTree.setCheckedNodes([]);
      }
    },
    rightTreeChecked(currentNode, { checkedNodes }) {
      this.rightTreeCheckedNodes = Array.from(
        new Set(this.rightTreeCheckedNodes.concat(checkedNodes))
      );
      let checkedId = checkedNodes.map((item) => item.auth_id);
      if (!checkedId.length || !checkedId.includes(currentNode.auth_id)) {
        this.rightTreeCheckedNodes = this.rightTreeCheckedNodes.filter(
          (item) => {
            return item.auth_id !== currentNode.auth_id;
          }
        );
      }
      this.dckeys = this.rightTreeCheckedNodes.map((item) => item.auth_id);
      this.changeChecked();
    },
    changeChecked() {
      this.rightTreeData.filter((item) => {
        return !this.rightTreeCheckedNodes
          .map((item) => {
            return item.auth_id;
          })
          .includes(item.auth_id);
      }).length > 0
        ? (this.checked = false)
        : (this.checked = true);
    },
  },
};
</script>
<style lang="less" scoped>
.FunctionalAuthority {
  main {
    background: #fff;
    padding: 10px;
    .el-table {
      min-height: calc(100vh - 280px);
      margin-bottom: 10px;
    }
    .el-pagination {
      display: flex;
      justify-content: end;
    }
  }
}
</style>
<style lang="less">
.funtional-authority-dialog {
  .el-dialog__header {
    padding: 20px 0;
    border-bottom: 1px solid #e9e9e9;
    .dialog-title {
      padding: 0 16px;
      .el-breadcrumb {
        font-size: 12px;
        padding-bottom: 0px !important;
      }
    }
  }
  .el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
    .dialog-main {
      display: flex;
      border-bottom: 1px solid #e9e9e9;
      h2 {
        font-weight: normal;
        font-size: 14px;
        padding: 10px 0;
      }
      & > div {
        flex: 1;
        height: calc(100vh - 300px);
        &:first-child {
          border-right: 1px solid #e9e9e9;
        }
      }
      .main-right {
        padding-left: 20px;
        .right-top {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }
}
</style>
